from flask import Blueprint, jsonify, current_app, request
from app.services.system_monitor import (
    get_system_info, 
    get_system_status, 
    get_box_id,
    get_system_metrics,
    get_process_list
)
from app.models.system import SystemStatus

system_bp = Blueprint('system', __name__)

@system_bp.route('/info', methods=['GET'])
def system_info():
    """获取系统基本信息（按需启动系统监控）"""
    # 启动基础监控服务
    if hasattr(current_app, 'service_manager'):
        current_app.service_manager.start_service_on_demand('system_monitor', auto_stop_timeout=300)
    
    info = get_system_info()
    return jsonify({'status': 'success', 'data': info})

@system_bp.route('/box-id', methods=['GET'])
def box_id():
    """获取设备唯一标识符"""
    return jsonify({'box_id': get_box_id()})

@system_bp.route('/status', methods=['GET'])
def system_status():
    """获取系统实时状态（按需启动系统监控）"""
    # 启动基础监控服务
    if hasattr(current_app, 'service_manager'):
        current_app.service_manager.start_service_on_demand('system_monitor', auto_stop_timeout=300)
    
    return jsonify(get_system_status())

@system_bp.route('/metrics', methods=['GET'])
def system_metrics():
    """获取详细的系统性能指标（按需启动实时监控）"""
    # 启动实时监控服务
    if hasattr(current_app, 'service_manager'):
        current_app.service_manager.start_service_on_demand('realtime_monitor', auto_stop_timeout=600)
    
    metrics = get_system_metrics()
    return jsonify({'status': 'success', 'data': metrics})

@system_bp.route('/processes', methods=['GET'])
def system_processes():
    """获取当前运行的进程列表（按需启动系统监控）"""
    # 启动基础监控服务
    if hasattr(current_app, 'service_manager'):
        current_app.service_manager.start_service_on_demand('system_monitor', auto_stop_timeout=300)
    
    processes = get_process_list()
    return jsonify({'status': 'success', 'data': processes})

@system_bp.route('/resources', methods=['GET'])
def system_resources():
    """获取系统资源使用情况（按需启动系统监控）"""
    # 启动基础监控服务
    if hasattr(current_app, 'service_manager'):
        current_app.service_manager.start_service_on_demand('system_monitor', auto_stop_timeout=300)
    
    return jsonify(get_system_status())

@system_bp.route('/history', methods=['GET'])
def system_history():
    """获取历史系统状态数据"""
    try:
        # 默认返回最近1小时的数据
        hours = int(request.args.get('hours', 1))
        # 限制查询范围，避免返回过多数据
        if hours > 24:
            hours = 24
            
        # 查询历史数据
        from datetime import datetime, timedelta
        end_time = datetime.now()
        start_time = end_time - timedelta(hours=hours)
        
        records = SystemStatus.query.filter(
            SystemStatus.created_at >= start_time,
            SystemStatus.created_at <= end_time
        ).all()
        
        # 格式化响应数据
        result = {
            'timestamps': [],
            'cpu': [],
            'memory': [],
            'disk': [],
            'temperature': []
        }
        
        for record in records:
            result['timestamps'].append(record.created_at.isoformat())
            result['cpu'].append(record.cpu_percent)
            result['memory'].append(record.memory_percent)
            result['disk'].append(record.disk_percent)
            result['temperature'].append(record.temperature)
            
        return jsonify(result)
    except Exception as e:
        current_app.logger.error(f"获取历史数据失败: {str(e)}")
        return jsonify({'error': str(e)}), 500

@system_bp.route('/reboot', methods=['POST'])
def system_reboot():
    """重启系统"""
    try:
        # 记录重启请求
        current_app.logger.info("收到系统重启请求")
        
        # 在生产环境中执行实际重启
        if not current_app.debug:
            import os
            # 使用非阻塞方式重启系统
            os.system('(sleep 2 && sudo reboot) &')
            return jsonify({'message': '系统将在2秒后重启'}), 200
        else:
            return jsonify({'message': '调试模式下，重启命令未执行'}), 200
    except Exception as e:
        current_app.logger.error(f"重启系统失败: {str(e)}")
        return jsonify({'error': f'重启系统失败: {str(e)}'}), 500

# 服务管理API
@system_bp.route('/services/start/<service_name>', methods=['POST'])
def start_service(service_name):
    """手动启动指定服务"""
    if not hasattr(current_app, 'service_manager'):
        return jsonify({'status': 'error', 'message': '服务管理器未初始化'}), 500
    
    timeout = request.json.get('timeout', 300) if request.is_json else 300
    success = current_app.service_manager.start_service_on_demand(service_name, auto_stop_timeout=timeout)
    
    if success:
        return jsonify({
            'status': 'success', 
            'message': f'服务 {service_name} 启动成功',
            'timeout': timeout
        })
    else:
        return jsonify({'status': 'error', 'message': f'服务 {service_name} 启动失败'}), 500

@system_bp.route('/services/stop/<service_name>', methods=['POST'])
def stop_service(service_name):
    """手动停止指定服务"""
    if not hasattr(current_app, 'service_manager'):
        return jsonify({'status': 'error', 'message': '服务管理器未初始化'}), 500
    
    success = current_app.service_manager.stop_service(service_name)
    
    if success:
        return jsonify({'status': 'success', 'message': f'服务 {service_name} 停止成功'})
    else:
        return jsonify({'status': 'error', 'message': f'服务 {service_name} 停止失败'}), 500

@system_bp.route('/services/status', methods=['GET'])
def services_status():
    """获取所有服务状态"""
    if not hasattr(current_app, 'service_manager'):
        return jsonify({'status': 'error', 'message': '服务管理器未初始化'}), 500
    
    active_services = current_app.service_manager.get_active_services()
    return jsonify({
        'status': 'success',
        'data': {
            'active_services': list(active_services),
            'total_active': len(active_services)
        }
    })

@system_bp.route('/services/websocket/init', methods=['POST'])
def init_websocket():
    """按需初始化WebSocket服务"""
    if not hasattr(current_app, 'service_manager'):
        return jsonify({'status': 'error', 'message': '服务管理器未初始化'}), 500
    
    success = current_app.service_manager.start_service_on_demand('websocket_service', auto_stop_timeout=1800)  # 30分钟超时
    
    if success:
        return jsonify({'status': 'success', 'message': 'WebSocket服务已启动'})
    else:
        return jsonify({'status': 'error', 'message': 'WebSocket服务启动失败'}), 500 